package com.byq.ai.agentlab.controller;

import com.byq.ai.agentlab.entity.Task;
import com.byq.ai.agentlab.entity.TaskStatus;
import com.byq.ai.agentlab.repository.TaskRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
public class TestController {

    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TaskRepository taskRepository;

    @GetMapping("/db")
    public Map<String, Object> testDbConnection() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            logger.info("开始测试数据库连接...");
            
            // 创建一个测试任务
            Task task = new Task();
            task.setName("测试任务");
            task.setDescription("这是一个测试任务，用于验证数据库连接和向量功能");
            task.setStatus(TaskStatus.PENDING);
            
            // 创建一个简单的向量
            float[] embedding = new float[1536];
            for (int i = 0; i < 1536; i++) {
                embedding[i] = (float) (Math.random() * 2 - 1); // 随机值在 -1 到 1 之间
            }
            task.setEmbedding(embedding);
            
            logger.info("准备保存任务到数据库...");
            
            // 保存到数据库
            Task savedTask = taskRepository.save(task);
            
            logger.info("任务已成功保存到数据库，ID: {}", savedTask.getTaskId());
            
            result.put("success", true);
            result.put("message", "数据库连接成功，测试任务已保存");
            result.put("taskId", savedTask.getTaskId());
        } catch (Exception e) {
            logger.error("数据库连接测试失败", e);
            
            result.put("success", false);
            result.put("message", "数据库连接失败: " + e.getMessage());
            result.put("error", e.toString());
            result.put("stackTrace", e.getStackTrace());
        }
        
        return result;
    }
} 